package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import model.ContactModel;
import model.ContactsModel;
import view.View;

public class Controller implements ActionListener, WindowListener,
		MouseListener {

	private View view;
	private ContactsModel model;

	/**
	 * Contractor
	 * @param model
	 * @param view
	 */
	public Controller(ContactsModel model, View view) {
		this.view = view;
		this.model = model;
		final long start = System.nanoTime();   
		//this.loadCsv();
		this.model.initLoadDataCallables();
		final long end = System.nanoTime();   
		System.out.println((end - start ) / 1.0e9);
		for (ContactModel contact : this.model.getContacts()) {
			view.defaultListModel.addElement(contact.getPersonName());
		}
	}
	
	/**
	 * Create Contact Model based on all fields
	 * @return
	 */
	public ContactModel initModel() {
		String firstName = this.view.textFieldFirstName.getText().trim();
		String lastName = this.view.textFieldLastName.getText().trim();
		String homeAddress = this.view.textFieldHomeAddress.getText().trim();
		String companyAddress = this.view.textFieldCompanyAddress.getText().trim();
		String personalPhoneMobile = this.view.textFieldPersonalPhoneMobile
				.getText().trim();
		String personalPhoneHome = this.view.textFieldPersonalPhoneHome.getText()
				.trim();
		String professionalPhoneMobile = this.view.textFieldProfessionalPhoneMobile
				.getText().trim();
		String professionalPhoneOffice = this.view.textFieldProfessionalPhoneOffice
				.getText().trim();
		String homePage = this.view.textFieldHomePage.getText().trim();
		String emailProfessional = this.view.textFieldEmailProfessional.getText()
				.trim();
		String emailPersonal = this.view.textFieldEmailPersonal.getText().trim();
		String other = this.view.textFieldOther.getText().trim();
		String imagePath = this.view.textFieldImage.getText().trim();
		String group = this.view.comboBoxGroup.getSelectedItem().toString();

		// it must fill the full name
		if (firstName.isEmpty() || lastName.isEmpty()) {
			JOptionPane.showMessageDialog(null,
					"The full name could not be empty");
			return null;

		}

		ContactModel contactModel = new ContactModel(firstName, lastName,
				homeAddress, companyAddress, personalPhoneMobile,
				personalPhoneHome, professionalPhoneMobile,
				professionalPhoneOffice, homePage, emailProfessional,
				emailPersonal, other, imagePath, group, this.model.getCount());
		return contactModel;
	}

	/**
	 * Implementation of ActionListener
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if (arg0.getSource() == this.view.buttonAddContact) {
			ContactModel contactModel = this.initModel();
			if (contactModel != null) {
				if (this.model.getCurrentModel() != null) {
					this.model.updateContact(this.model.getCurrentModel(),
							contactModel);
					this.view.buttonAddContact.setEnabled(false);
					this.view.buttonCreateContact.setEnabled(true);
					this.view.enableform(false);
					view.clearform();
				} else {
					this.model.addContact(contactModel);
					this.view.buttonAddContact.setEnabled(false);
					this.view.buttonCreateContact.setEnabled(true);
					this.view.enableform(false);
					view.clearform();
				}
			}
		} else if (arg0.getSource() == this.view.buttonDeleteContact) {

			if (this.model.getCurrentModel() != null) {
				this.model.deleteContact(this.model.getCurrentModel() );
				view.buttonAddContact.setEnabled(false);
				view.buttonCreateContact.setEnabled(true);
				view.buttonDeleteContact.setEnabled(false);
				view.buttonModifyContact.setEnabled(false);
				view.clearform();
			}
		} else if (arg0.getSource() == this.view.buttonModifyContact) {

			view.buttonAddContact.setEnabled(true);
			view.buttonModifyContact.setEnabled(false);
			view.buttonCreateContact.setEnabled(true);
			view.buttonDeleteContact.setEnabled(false);
			view.enableform(true);

		} else if (arg0.getSource() == this.view.buttonClearContact) {
			view.clearform();
		} else if (arg0.getSource() == this.view.buttonCreateContact) {
			view.clearform();
			view.buttonAddContact.setEnabled(true);
			view.buttonModifyContact.setEnabled(false);
			view.buttonDeleteContact.setEnabled(false);
			view.buttonCreateContact.setEnabled(false);
			view.enableform(true);
			this.model.setCurrentModel(null);
		} else if (arg0.getSource() == this.view.buttonDisplayByAlphabetical){
			this.model.sortByAlpha();
		} else if (arg0.getSource() == this.view.buttonDisplayByGroup){
			this.model.sortByGroup();
		} else if (arg0.getSource() == this.view.buttonDisplayByCreatingTime){
			this.model.sortByCreate();
		}
		
		
		
		else {
			System.out.println(arg0.getSource());
		}

	}

	/**
	 * Implementation of WindowListener
	 */
	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowClosing(WindowEvent arg0) {
		int option = JOptionPane.showConfirmDialog(view,
				"Do you want to save the new contact with CSV file",
				"Notice Message", JOptionPane.OK_CANCEL_OPTION);

		if (JOptionPane.OK_OPTION == option) {
			try {
				this.model.saveFile();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			System.exit(0);
		} else {
			this.view.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		}
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	/**
	 * Implementation of MouseListener
	 */
	@Override
	public void mouseClicked(MouseEvent arg0) {
		if (arg0.getSource() == this.view.textFieldImage) {
			int value = this.view.fileChooserImage.showOpenDialog(this.view);
			if (value == 0) {
				ImageIcon image = new ImageIcon(this.view.fileChooserImage
						.getSelectedFile().getAbsolutePath());
				this.view.labelPhoto.setIcon(image);
				this.view.textFieldImage.setText(this.view.fileChooserImage
						.getSelectedFile().getAbsolutePath());
			}
		} else if (arg0.getSource() == this.view.listDisplayerContactPersonName) {
			int index = this.view.listDisplayerContactPersonName
					.getSelectedIndex();
			ContactModel currentContact = this.model.getContacts().get(index);
			this.model.setCurrentModel(currentContact);

			this.view.textFieldFirstName.setText(currentContact.getFirstName());
			this.view.textFieldLastName.setText(currentContact.getLastName());
			this.view.textFieldHomeAddress.setText(currentContact
					.getHomeAddress());
			this.view.textFieldCompanyAddress.setText(currentContact
					.getCompanyAddress());
			this.view.textFieldPersonalPhoneMobile.setText(currentContact
					.getPersonMobilePhone());
			this.view.textFieldPersonalPhoneHome.setText(currentContact
					.getPersonHomePhone());
			this.view.textFieldProfessionalPhoneMobile.setText(currentContact
					.getProfessionalMobilePhone());
			this.view.textFieldProfessionalPhoneOffice.setText(currentContact
					.getProfessionalOfficePhone());
			this.view.textFieldHomePage.setText(currentContact.getHomePage());
			this.view.textFieldEmailPersonal.setText(currentContact
					.getPersonalEmail());
			this.view.textFieldEmailProfessional.setText(currentContact
					.getProfessionalEmail());
			this.view.comboBoxGroup.setSelectedItem(currentContact.getGroup());
			this.view.textFieldImage.setText(currentContact.getImagePath());
			ImageIcon image = new ImageIcon(currentContact.getImagePath());
			this.view.labelPhoto.setIcon(image);
			this.view.textFieldOther.setText(currentContact.getOther());

			this.view.buttonModifyContact.setEnabled(true);
			this.view.buttonDeleteContact.setEnabled(true);
			this.view.buttonAddContact.setEnabled(false);
			this.view.buttonCreateContact.setEnabled(true);
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

}
